package cn.tedu.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    static int i = 0;
    public static void main(String[] args) throws InterruptedException {

        // ReentrantLock表示的是一个重入锁
        Lock lock = new ReentrantLock(true);
        new Thread(new Add(lock)).start();
        new Thread(new Add(lock)).start();

        // 在Add执行完成之后, 主线程需要等待
        Thread.sleep(3000);
        System.out.println(i);
    }
}

class Add implements Runnable {
    private Lock lock;

    public Add(Lock lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        // synchronized (Add.class)
        lock.lock();
        {
            for (int i = 0; i < 10000; ++i) {
                LockDemo.i++;
            }
        }
        lock.unlock();
    }
}
